#!/usr/bin/python3
# coding=utf-8
# -*- coding: utf-8 -*-
import re
from sys import argv
from enum import Enum
from src.transfer.gps_transfer import wgs84togcj02
from src.transfer.gps_transfer import gcj02towgs84
from src.transfer.gps_transfer import bd09togcj02
import argparse
import os


class DataAnalyse(object):

    def data_analyse_mark(self, line):
        remarks = re.findall(r"[0-9a-zA-z]+", line)
        if len(remarks) > 1:
            return remarks[0]
        return ""

    # 分析每行数据中的location 数据
    def data_analyse_locations(self, line):
        locations = re.findall(r"\d+\.\d+", line)
        index = 0
        locations_count = len(locations)
        nlocations = []
        while locations_count % 2 == 0 and index < locations_count:
            location = {}
            log = locations[index]
            lat = locations[index + 1]
            location['log'] = log
            location['lat'] = lat
            nlocations.append(location)
            index += 2
        return nlocations

        # 数据解析
    def data_analyse(self, file_path):
        file = open(file_path)
        line_number = 0
        objects = []
        while 1:
            line = file.readline()
            if not line:
                break
            object = {}
            object['remark'] = self.data_analyse_mark(line)
            object['locations'] = self.data_analyse_locations(line)
            object['index'] = line_number
            objects.append(object)
            line_number += 1
        return objects


class GPSTransferType(Enum):
    wgs84 = 1
    gcj02 = 2
    bd09 = 3
    none = 0

    def get_transfer_type(type):
        if float(type) == 1:
            return GPSTransferType.wgs84
        elif float(type) == 2:
            return GPSTransferType.gcj02
        elif float(type) == 3:
            return GPSTransferType.bd09
        return GPSTransferType.none

# 点位坐标体系装换


class GPSTransfer(object):

    def location_transfer(self, location, from_type, to_type):
        """
        经纬度装换函数
        :location 经纬度坐标集合
        :from_type 待转换坐标类型
        :to_type 转换类型
        """
        location_log = float(location['log'])
        location_lat = float(location['lat'])
        location_tupe = (0.0, 0.0)

        if from_type == to_type:
            return location

        if from_type is GPSTransferType.wgs84 and to_type is GPSTransferType.gcj02:
            location_tupe = wgs84togcj02(location_log, location_lat)
        if from_type is GPSTransferType.gcj02 and to_type is GPSTransferType.wgs84:
            location_tupe = gcj02towgs84(location_log, location_lat)
        if from_type is GPSTransferType.bd09 and to_type is GPSTransferType.gcj02:
            location_tupe = bd09togcj02(location_log, location_lat)
        if from_type is GPSTransferType.bd09 and to_type is GPSTransferType.wgs84:
            (log, lat) = bd09togcj02(location_log, location_lat)
            location_tupe = gcj02towgs84(log, lat)

        nlocation = {'log': 0, 'lat': 0}
        if location_tupe[0] == 0.0 and location_tupe[1] == 0.0:
            return nlocation
        nlocation['log'] = location_tupe[0]
        nlocation['lat'] = location_tupe[1]
        return nlocation

    def data_transfer(self, objects,
                      from_type=GPSTransferType.wgs84,
                      to_type=GPSTransferType.gcj02):
        nobjects = []
        for object in objects:
            nlocations = []
            for location in object['locations']:
                nlocation = self.location_transfer(location,
                                                   from_type,
                                                   to_type)
                nlocations.append(nlocation)
            object['locations'] = nlocations
            nobjects.append(object)
        return nobjects

    # 数据响应输出

    def data_response_out(self, objects, out_file):
        file_out = open(out_file, "w+")
        for object in objects:
            line = object['remark'] + "\t"
            for location in object['locations']:
                line += str(location['log']) + "\t" + \
                    str(location['lat'])
            line += "\n"
            file_out.write(line)
        file_out.close()

    def sql_formatter(self, grid_id, pos_x, pos_y):
        sql = "UPDATE `t_ledger` set `longitude` = " + "'" + \
            str(pos_x) + "'" + ", `latitude` = " + "'" + str(pos_y) + \
            "'" + " where id = " + "'" + str(grid_id) + "';\n"
        return sql

    def data_sql_response_out(self, objects, out_file):
        file_out = open(out_file + "_sql.txt", "w+")
        for object in objects:
            mask = object['remark']
            for location in object['locations']:
                line = sql_formatter(mask, location['log'], location['lat'])
                file_out.write(line)
                break
        file_out.close()

    def transfer_file(self, file_in, file_out, type_from, type_to):
        if isinstance(type_from, str):
            type_from = GPSTransferType.get_transfer_type(type_from)
        if isinstance(type_to, str):
            type_to = GPSTransferType.get_transfer_type(type_to)

        objs = DataAnalyse().data_analyse(file_in)
        objects = self.data_transfer(objs, type_from, type_to)
        self.data_response_out(objects, file_out)
        return file_out


if __name__ == '__main__':
    file_path = os.path.dirname(__file__) + '/12.txt'
    if len(argv) >= 2:
        file_out = file_path.split(".txt")[0] + "_out.txt"
    else:
        file_out = argv[2]

    objects = GPSTransfer().transfer_file(file_path,
                                          file_out,
                                          GPSTransferType.gcj02,
                                          GPSTransferType.wgs84)
    print(objects)
